<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label>
            <AInput v-model="searchFrom.productName" placeholder="产品名称" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label>
            <AInput v-model="searchFrom.specModel" placeholder="规格型号" allow-clear />
          </AFormItem>
        </ACol>
        <ACol :span="6">
          <AFormItem hide-label>
            <AInput v-model="searchFrom.unit" placeholder="单位" allow-clear />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 2])" type="outline" @click="openEdit('新增')">新增</AButton>
          <tableImp
            v-if="isAuth([1, 2])"
            imp-url="/produce/erpProductImport"
            :file-temp="() => onExport('template')"
            :other-param="{ productType: 0 }"
            @end-call-back="onSearch"
          ></tableImp>
          <ATooltip
            v-if="isAuth([1, 2])"
            :disabled="!isEmpty(selectedRowKeys)"
            content="请选择产品"
          >
            <AButton
              type="outline"
              status="normal"
              :disabled="isEmpty(selectedRowKeys)"
              @click="fastGenerate('quotation')"
            >
              生成报价单
            </AButton>
          </ATooltip>
          <ATooltip
            v-if="isAuth([1, 2])"
            :disabled="!isEmpty(selectedRowKeys)"
            content="请选择产品"
          >
            <AButton
              type="outline"
              status="normal"
              :disabled="isEmpty(selectedRowKeys)"
              @click="fastGenerate('productMaterial')"
            >
              生成采购单
            </AButton>
          </ATooltip>
          <ATooltip
            v-if="isAuth([1, 2])"
            :disabled="!isEmpty(selectedRowKeys)"
            content="请选择产品"
          >
            <AButton
              type="outline"
              status="normal"
              :disabled="isEmpty(selectedRowKeys)"
              @click="fastGenerate('salesBill')"
            >
              生成订单
            </AButton>
          </ATooltip>
          <ATooltip
            v-if="isAuth([1, 2])"
            :disabled="!isEmpty(selectedRowKeys)"
            content="请选择产品"
          >
            <AButton status="danger" @click="batchDel()">批量删除</AButton>
          </ATooltip>
        </ASpace>
        <ASpace>
          <AButton type="primary" :loading="exportLoad" @click="onExport('table')">导出</AButton>
          <ADropdownButton>
            {{ ['名称排序', '时间排序'][orderBy] }}
            <template #icon>
              <icon-down />
            </template>
            <template #content>
              <ADoption
                :value="0"
                @click="
                  () => {
                    orderBy = 0
                    onSearch()
                  }
                "
              >
                名称排序
              </ADoption>
              <ADoption
                :value="1"
                @click="
                  () => {
                    orderBy = 1
                    onSearch()
                  }
                "
              >
                时间排序
              </ADoption>
            </template>
          </ADropdownButton>
        </ASpace>
      </div>
      <ATable
        ref="tableRef"
        v-model:selected-keys="selectedRowKeys"
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        column-resizable
        size="small"
        :row-selection="{
          type: 'checkbox',
          showCheckedAll: true
        }"
        row-key="productId"
      >
        <template #columns>
          <ATableColumn title="产品名称" data-index="productName" :width="120"></ATableColumn>
          <ATableColumn title="规格型号" data-index="specModel" :width="120"></ATableColumn>
          <ATableColumn title="类型" data-index="productCategory" :width="100"></ATableColumn>
          <ATableColumn title="单位" data-index="unit" :width="80" align="center"></ATableColumn>
          <!-- <ATableColumn title="材质代码" data-index="materialCode" :width="100"> </ATableColumn>
          <ATableColumn title="材质名称" data-index="materialDesc" :width="100"> </ATableColumn>
          <ATableColumn title="楞型" data-index="fluteType" :width="100"> </ATableColumn> -->
          <ATableColumn title="备注" data-index="remark" :width="100"></ATableColumn>
          <!-- <ATableColumn title="创建人" data-index="createdBy" :width="130" align="center">
          </ATableColumn>
          <ATableColumn title="创建时间" data-index="createdDt" :width="160" align="center">
            <template #cell="{ record }">
              <div>{{ dayjs(record.createdDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn> -->
          <ATableColumn title="更新时间" data-index="remark" :width="120" align="center">
            <template #cell="{ record }">
              <div>{{ dayjs(record.updatedDt).format('YYYY-MM-DD') }}</div>
            </template>
          </ATableColumn>
          <ATableColumn
            v-if="isAuth([1, 2])"
            title="操作"
            :width="145"
            align="center"
            fixed="right"
          >
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></EditPopupForm>
    <addQuotation
      v-model:visible="fastGenerateModal.quotation"
      title="新增报价单"
      :check-data="{ detailList: selectRows }"
      from-module="product"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></addQuotation>
    <addPurchaseFinished
      v-model:visible="fastGenerateModal.productMaterial"
      title="新增采购单"
      :check-data="{ detailList: selectRows }"
      from-module="product"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></addPurchaseFinished>
    <addSale
      v-model:visible="fastGenerateModal.salesBill"
      title="新增销售订单"
      :check-data="{ detailList: selectRows }"
      from-module="product"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></addSale>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import dayjs from 'dayjs'
import { Message, Modal, TableInstance } from '@arco-design/web-vue'
import { isAuth } from '@renderer/utils/auth'
import {
  batchDelProduct,
  delProduct,
  getProductAllList,
  getProductPageList,
  ProductResItem,
  ProductSearch
} from '@renderer/api/salesDep'
import tableImp from '@renderer/components/table/import.vue'
import addQuotation from '@renderer/views/salesDepartment/quotation/editPopupForm.vue'
import addSale from '@renderer/views/salesDepartment/salesBill/editPopupForm.vue'
import addPurchaseFinished from '@renderer/views/purchasingDepartment/purchaseFinished/editPopupForm.vue'
import { cloneDeep, isEmpty } from 'lodash-es'
import { downloadFile } from '@renderer/utils/mixins'
import { getTemplateUrl } from '@renderer/api/common'

const searchFrom = ref<ProductSearch>({
  productType: 0
})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<ProductResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const fastGenerateModal = ref({
  quotation: false,
  salesBill: false,
  productMaterial: false
})
const selectedRowKeys = ref<string[]>([])
const selectRows = ref<any[]>([])
const orderBy = ref(0)
const tableRef = ref<TableInstance>()

onMounted(() => {
  getTableData()
})

function clearTableSelect() {
  tableRef.value?.selectAll(false)
  selectedRowKeys.value = []
  selectRows.value = []
}

async function getTableData() {
  searchFrom.value.productType = 0
  const res = await getProductPageList({
    ...searchFrom.value,
    ...pageParam,
    orderBy: orderBy.value
  })
  tableData.value = res.data.list
  pageParam.totalCount = res.data.totalCount!
}

function onSearch() {
  pageParam.currentPage = 1
  getTableData()
}

function onReset() {
  searchFrom.value = {
    productType: 0
  }
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}

function openEdit(title: string) {
  rowData.value = {}
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref<ProductResItem>()

function rowEvent(row: ProductResItem, type: string) {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delProduct({ productId: row.productId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break

    default:
      break
  }
}

function batchDel() {
  batchDelProduct({ idList: selectedRowKeys.value }).then(() => {
    Message.success('删除成功')
    onSearch()
    clearTableSelect()
  })
}

const exportLoad = ref(false)

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  exportLoad.value = true
  const headerData = [
    { title: '产品名称', value: 'productName', width: 180 },
    { title: '规格型号', value: 'specModel' },
    { title: '类型', value: 'productCategory' },
    { title: '单位', value: 'unit' },
    // { title: '材质代码', value: 'materialCode' },
    // { title: '材质名称', value: 'materialDesc', width: 180 },
    // { title: '楞型', value: 'fluteType' },
    { title: '备注', value: 'remark' }
  ]
  let excelData: ProductResItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '产品数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getProductAllList(searchFrom.value)
        excelData = res.data.list.map((item, index) => {
          item.index = index + 1
          return item
        })
        import('@renderer/utils/vendor').then((excel) => {
          excel.exportExcel(excelData, headerData, fileTitle)
          exportLoad.value = false
        })
      }
      break
    case 'template':
      getTemplateUrl('/produce/erpProductTemplateUrl').then((res) => {
        downloadFile(res.data)
      })
      break
    default:
      break
  }
}

function fastGenerate(type: 'quotation' | 'productMaterial' | 'salesBill') {
  fastGenerateModal.value[type] = true
  const tempData = cloneDeep(tableData.value)
  selectRows.value = tempData.filter((item) => selectedRowKeys.value.includes(item.productId!))
  if (type === 'productMaterial') {
    selectRows.value = selectRows.value.map((item) => {
      item.materialStockId = item.productId
      item.spec = item.specModel
      return item
    })
  }
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
